#!/usr/bin/with-contenv sh

set -u # Treat unset variables as an error.

# Make sure we appear with a proper name under `ps`.
if [ ! -L "$0" ]; then
    SV_NAME="$(basename "$(pwd)")"
    ln -sf run "$SV_NAME"
    exec ./"$SV_NAME" "$@"
fi

log() {
    echo "[$(basename "$0")] $*"
}

hash() {
    stat -c '%n %s %Y' "$@" | md5sum | cut -d' ' -f1
}

restart_nginx() {
    log "Restarting nginx..."
    /bin/s6-svc -h /var/run/s6/services/nginx
}

restart_x11vnc() {
    log "Restarting x11vnc..."
    /usr/bin/x11vnc -R stop
}

# Disable service if secure connection disabled.
if [ "${SECURE_CONNECTION:-0}" -ne 1 ]; then
    log "disabling service: secure connection not enabled."
    touch /var/run/s6/services/certsmonitor/down
    s6-svc -xd /var/run/s6/services/certsmonitor
    exit 0
fi

log "starting..."

WEB_CERTS="/config/certs/web-privkey.pem /config/certs/web-fullchain.pem"
VNC_CERTS="/config/certs/vnc-server.pem"
DH_PARAMS="/config/certs/dhparam.pem"

WEB_CERTS_HASH="$(hash $WEB_CERTS)"
VNC_CERTS_HASH="$(hash $VNC_CERTS)"
DH_PARAMS_HASH="$(hash $DH_PARAMS)"

while true; do
    # Check for certificate changes every 5 seconds.
    sleep 5

    # Get new hashes.
    WEB_CERTS_NEW_HASH="$(hash $WEB_CERTS)"
    VNC_CERTS_NEW_HASH="$(hash $VNC_CERTS)"
    DH_PARAMS_NEW_HASH="$(hash $DH_PARAMS)"

    # Restart nginx if certificates changed.
    if [ "$WEB_CERTS_NEW_HASH" != "$WEB_CERTS_HASH" ]; then
        log "Web certificates changed."
        restart_nginx
    elif [ "$DH_PARAMS_NEW_HASH" != "$DH_PARAMS_HASH" ]; then
        log "DH parameters changed."
        restart_nginx
    fi

    # Restart x11vnc if certificates changed.
    if [ "$VNC_CERTS_NEW_HASH" != "$VNC_CERTS_HASH" ]; then
        log "VNC certificates changed."
        restart_x11vnc
    fi

    WEB_CERTS_HASH="$WEB_CERTS_NEW_HASH"
    VNC_CERTS_HASH="$VNC_CERTS_NEW_HASH"
    DH_PARAMS_HASH="$DH_PARAMS_NEW_HASH"
done

# vim: set ft=sh :
